<template>
  <div class="employee-detail">
    <a-card title="员工详情">
      <template #extra>
        <a-button @click="goBack">返回列表</a-button>
        <a-button type="primary" @click="goToEdit" style="margin-left: 10px">编辑</a-button>
      </template>

      <a-descriptions bordered :column="2">
        <a-descriptions-item label="姓名">{{ employeeInfo.name }}</a-descriptions-item>
        <a-descriptions-item label="工号">{{ employeeInfo.employeeId }}</a-descriptions-item>
        <a-descriptions-item label="性别">{{ employeeInfo.gender === 1 ? '男' : '女' }}</a-descriptions-item>
        <a-descriptions-item label="部门">{{ employeeInfo.department }}</a-descriptions-item>
        <a-descriptions-item label="职位">{{ employeeInfo.position }}</a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="employeeInfo.status === 1 ? 'green' : 'red'">
            {{ employeeInfo.status === 1 ? '在职' : '离职' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="手机号">{{ employeeInfo.phone }}</a-descriptions-item>
        <a-descriptions-item label="邮箱">{{ employeeInfo.email }}</a-descriptions-item>
        <a-descriptions-item label="入职日期">{{ employeeInfo.hireDate }}</a-descriptions-item>
        <a-descriptions-item label="备注" :span="2">
          {{ employeeInfo.remark || '无' }}
        </a-descriptions-item>
      </a-descriptions>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { getEmployeeDetail } from '@/api/employee'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const employeeInfo = ref({
  id: '',  // 确保包含ID字段
  name: '',
  employeeId: '',
  gender: 1,
  department: '',
  position: '',
  status: 1,
  phone: '',
  email: '',
  hireDate: '',
  remark: ''
})

// 获取员工详情
const fetchEmployeeDetail = async () => {
  loading.value = true
  try {
    console.log('正在获取员工ID:', route.params.id) // 调试日志
    const res = (await getEmployeeDetail(route.params.id)).data.data.list[route.params.id-1]
    console.log('获取到的员工数据:', res) // 调试日志


    if (!res.id) {
      throw new Error('返回数据缺少ID字段')
    }
    employeeInfo.value = res
  } catch (error) {
    console.error('获取详情失败:', error)
    message.error(`获取详情失败: ${error.message}`)
    router.push('/employee/list')
  } finally {
    loading.value = false
  }
}

// 跳转编辑页
const goToEdit = () => {
  if (!employeeInfo.value.id) {
    message.warning('等待数据加载完成')
    return
  }
  router.push(`/employee/edit/${employeeInfo.value.id}`)
}

// 返回列表
const goBack = () => {
  router.push('/employee/list')
}

onMounted(() => {
  if (!route.params.id) {
    message.error('缺少员工ID参数')
    router.push('/employee/list')
    return
  }
  fetchEmployeeDetail()
})
</script>

<style scoped>
.employee-detail {
  padding: 20px;
}

.ant-descriptions {
  margin-top: 20px;
}
</style>